package com.hmall.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author liuyp
 * @since 2025/9/2
 */
// @Component
public class DemoGlogalFilter implements GlobalFilter, Ordered {
    /**
     * 过滤方法
     * @param exchange 对象里包含了request对象和response对象
     * @param chain 过滤器链，用于放行的
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //拿到request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求的数据
        //  获取请求的资源路径
        String path = request.getURI().getPath();
        System.out.println("path = " + path);
        //  获取请求头
        String userAgent = request.getHeaders().getFirst("User-Agent");
        System.out.println("userAgent = " + userAgent);

        //设置响应信息
        //  如果要放行
        // return chain.filter(exchange);

        //  如果不放行：通常要设置响应状态码
        // response.setRawStatusCode(401);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
